/** 
 * 权限控制
 * 判定用户是否拥有访问权限
 * 判定token是否存在
 */
import { Component } from 'react';
import { PageLoading } from '@ant-design/pro-layout';
import type { CurrentUser } from '@/models/user';
import { ConnectProps, Redirect } from 'umi';
import { connect } from 'umi';
import type { ConnectState } from '@/models/connect';
import { stringify } from 'querystring';

type SecurityLayoutProps = {
  loading?: boolean;
  currentUser?: CurrentUser;
} & ConnectProps;

type SecurityLayoutState = {
  isReady: boolean
}

class SecurityLayout extends Component<SecurityLayoutProps, SecurityLayoutState> {
  
  state: SecurityLayoutState = {
    isReady: false
  }

  componentDidMount() {
    this.setState({
      isReady: true
    })
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent'
      })
    }
  }

  render() {
    const { isReady } = this.state;
    const { children, loading, currentUser } = this.props;
    // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）
    const isLogin = currentUser && currentUser.userid;
    console.log(11111111111111111111111111111111111111111)
    const queryString = stringify({
      redirect: window.location.href
    })

    if((!isLogin && loading) || !isReady) {
      return <PageLoading />
    }
    if(!isLogin && window.location.pathname !== '/user/login') {
      return <Redirect to={`/user/login?${queryString}`} />
    }
    return children;
  }
}

export default connect(({ user, loading }: ConnectState) => ({
  currentUser: user.currentUser,
  loading: loading.models.user,
}))(SecurityLayout)